package com.tbsoft.ehr.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.tbsoft.ehr.model.AttendanceReport;
import com.tbsoft.ehr.model.PublicField;
import com.tbsoft.ehr.service.attendance.ReportService;
import com.tbsoft.ehr.util.ConfigProps;
/**
 * @desc 文件导出(doc,html,excel)
 * @author vastdream
 *
 */
public class ExportFileServlet extends HttpServlet {
	private String TMPL_PATH=(String)ConfigProps.getContextProperty("expr.tmpl.path");
	private Log log = LogFactory.getLog(getClass());
	private ApplicationContext context ;

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doProcess(req, resp);
	}
	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doProcess(req, resp);
	}
	protected void doProcess(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		String expType=req.getParameter("expType");
		String fileType=req.getParameter("fileType");
		log.info("{expType:"+expType+",fileType:"+fileType+"}");
		if("exp_atd_info".equals(expType)){
			String dateStart = req.getParameter("dateStart");
			String dateEnd = req.getParameter("dateEnd");
			String userName = req.getParameter("userName");
			
			ReportService reportService=(ReportService) context.getBean("reportService");
			List<AttendanceReport> list = reportService.getAttendacneInfo(dateStart, dateEnd, userName);
			Workbook workbook = new XSSFWorkbook(new FileInputStream(TMPL_PATH+File.separator+"atd_template.xlsx"));
			Sheet sheet = workbook.getSheet("Sheet1");
			int i=0,len=list.size();
			BigDecimal totNormalHours = new BigDecimal(0);
			BigDecimal totPayloadHours = new BigDecimal(0);
			DateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd");
			for(;i<len;i++){
				AttendanceReport adr = list.get(i);
				Row row = sheet.createRow(i+1);
				Cell cell = row.createCell(0);
				cell.setCellValue(dateFmt.format(adr.getDate()));
				cell = row.createCell(1);
				cell.setCellValue(adr.getUserId());
				cell = row.createCell(2);
				cell.setCellValue(adr.getUserName());
				cell = row.createCell(3);
				cell.setCellValue(adr.getServiceName());
				cell = row.createCell(4);
				cell.setCellValue(adr.getNormalHours().doubleValue());
				cell = row.createCell(5);
				cell.setCellValue(adr.getPayloadHours().doubleValue());
				cell = row.createCell(6);
				cell.setCellValue(adr.getLeaveHours().doubleValue());
				totNormalHours = totNormalHours.add(adr.getNormalHours());
				totPayloadHours=totPayloadHours.add(adr.getPayloadHours());
			}
			Row row = sheet.createRow(i+1);
			row.createCell(0);
			row.createCell(1);
			row.createCell(2);
			Cell cell=row.createCell(3);
			cell.setCellValue("汇总");
			cell=row.createCell(4);
			cell.setCellValue(totNormalHours.doubleValue());
			cell=row.createCell(5);
			cell.setCellValue(totPayloadHours.doubleValue());
			cell=row.createCell(6);
			cell.setCellValue(totNormalHours.subtract(totPayloadHours).doubleValue());
			resp.addHeader("Content-Disposition", "attachment;filename=" + new String((userName+"("+dateStart+"-"+dateEnd+").xlsx").getBytes("utf-8"),"ISO-8859-1"));
			resp.setContentType("application/octet-stream");
			workbook.write(resp.getOutputStream());
		}else if ("exp_atd_rpt".equals(expType)){
			String dateStart = req.getParameter("dateStart");
			String dateEnd = req.getParameter("dateEnd");
			String scId = req.getParameter("scId");
			Map pubfieldMap = (Map) this.getServletContext().getAttribute("PUBFIELD_MAP");
			ReportService reportService=(ReportService) context.getBean("reportService");
			reportService.setPubFieldMap(pubfieldMap);
			List<AttendanceReport> list = reportService.getAttendacneReport(dateStart, dateEnd, scId);
			Workbook workbook = new XSSFWorkbook(new FileInputStream(TMPL_PATH+File.separator+"atd_report_template.xlsx"));
			
			Map<String, Map> attendMap = (Map<String, Map>) pubfieldMap.get("ATTEND_TYPE");
			Sheet sheet = workbook.getSheet("Sheet1");
			//添加请假类型
			Row head = sheet.getRow(0);
			int headidx = 6;
			for(Iterator<?> itr= attendMap.entrySet().iterator();itr.hasNext();){
				Entry<?, ?> entry = (Entry<?, ?>) itr.next();
				head.getCell(++headidx).setCellValue(((PublicField)entry.getValue()).getName());
			}
			String scName="";
			int i=0,len=list.size();
			DateFormat dateFmt = new SimpleDateFormat("yyyy-MM");
			for(;i<len;i++){
				AttendanceReport adr = list.get(i);
				scName=adr.getServiceName();
				Row row = sheet.createRow(i+1);
				Cell cell = row.createCell(0);
				cell.setCellValue(dateFmt.format(adr.getDate()));
				cell = row.createCell(1);
				cell.setCellValue(adr.getUserId());
				cell = row.createCell(2);
				cell.setCellValue(adr.getUserName());
				cell = row.createCell(3);
				cell.setCellValue(adr.getServiceName());
				cell = row.createCell(4);
				cell.setCellValue(adr.getNormalHours().doubleValue());
				cell = row.createCell(5);
				cell.setCellValue(adr.getPayloadHours().doubleValue());
				cell = row.createCell(6);
				cell.setCellValue(adr.getLeaveHours().doubleValue());
				cell = row.createCell(7);
				cell.setCellValue(adr.getLateHits());
				headidx = 6;
				for(Iterator<?> itr= attendMap.entrySet().iterator();itr.hasNext();){
					Entry<?, ?> entry = (Entry<?, ?>) itr.next();
					cell = row.createCell(++headidx);
					cell.setCellValue(adr.getLeaveMap().get(entry.getKey()).doubleValue());
				}
			}
			resp.addHeader("Content-Disposition", "attachment;filename=" + new String((scName+"("+dateStart+"-"+dateEnd+").xlsx").getBytes("utf-8"),"ISO-8859-1"));
			resp.setContentType("application/octet-stream");
			workbook.write(resp.getOutputStream());
		}
		
	}
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
	}
	

}
